package service

import (
	"chat_gin/entity/dto"
	"chat_gin/entity/entity_user"
	"chat_gin/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// GetUserList 获取用户列表
func GetUserList(c *gin.Context) {
	param := dto.GetUserListParam{
		PageInfo: utils.DealPageInfo(c),
	}
	fmt.Println(param)
	data, total, _ := entity_user.GetUserList(param)
	c.JSON(http.StatusOK, gin.H{
		"total":   total,
		"data":    data,
		"status":  http.StatusOK,
		"message": "ok",
	})
}

// CreateUser 新建用户
func CreateUser(c *gin.Context) {
	userInfo := dto.NewUserInfo{
		Name:  c.Query("name"),
		Pwd:   c.Query("password"),
		Phone: c.Query("phone"),
	}
	resultJson := gin.H{
		"msg": "插入成功",
	}
	err := entity_user.AddUserInfo(userInfo)
	if err != nil {
		resultJson = gin.H{
			"msg": "插入数据错误",
			"err": err,
		}
	}
	// 把校验过后的用户数据传递给 entity 层进行处理
	// 检查用户是否已经存在,检查数据是否为空
	c.JSON(http.StatusOK, resultJson)
}

// DelUser 删除用户
func DelUser(c *gin.Context) {
	resultJson := gin.H{}
	useId, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		resultJson = gin.H{
			"msg": "失败",
			"err": err,
		}
	} else {
		// 操作删除用户
		err := entity_user.DelUserInfo(dto.DelUserInfo{
			Id: useId,
		})
		if err != nil {
			resultJson = gin.H{
				"msg": "删除失败",
				"err": err,
			}
		} else {
			resultJson = gin.H{
				"msg": "删除成功",
			}
		}
	}
	c.JSON(http.StatusOK, resultJson)
}

// ChangeUser 修改用户
func ChangeUser(c *gin.Context) {
	resultJson := gin.H{
		"msg": "修改成功",
	}
	getId, err1 := strconv.Atoi(c.Query("id"))
	fmt.Println("获取id", getId)
	if err1 != nil {
		resultJson = gin.H{
			"msg": "id数据错误",
			"err": err1,
		}
	}
	userInfo := dto.ChangeUserInfo{
		Name:  c.Query("name"),
		Pwd:   c.Query("password"),
		Phone: c.Query("phone"),
		Id:    getId,
	}

	err := entity_user.ChangeUserInfo(userInfo)
	if err != nil {
		resultJson = gin.H{
			"msg": "修改数据错误",
			"err": err,
		}
	}
	c.JSON(http.StatusOK, resultJson)
}
